<template>
  <div class="container">
    <div class="headerBox">
      <div class="firstBox">
        <div style="font-size: 5.86vw">{{ query.area }}</div>
        <div style="font-size: 4.26vw">{{ maskPhone(query.tel) }}</div>
      </div>
      <div
        style="
          width: 100%;
          height: 1px;
          background-color: #fff;
          margin: 3.73vw 0;
        "
      />
      <div class="secondBox">
        <div style="font-size: 4.26vw">客户：{{ maskName(query.name) }}</div>
        <div style="font-size: 3.73vw">{{ query.date }}</div>
      </div>
    </div>
    <div class="centerBox">
      <div class="centerLeft">
        <div class="baseTitle">基本套餐</div>
        <div class="baseContent1">
          <div>
            流量
            <span style="padding-left: 2.66vw">{{ query.flow }}G</span>
          </div>
          <div>
            语音
            <span style="padding-left: 2.66vw"> {{ query.voice }}min</span>
          </div>
          <div>
            宽带
            <span style="padding-left: 2.66vw">{{ query.broadband }}M</span>
          </div>
          <div>
            电视
            <span style="padding-left: 2.66vw">{{ query.television }}</span>
          </div>
        </div>
        <div class="driver" />
        <div class="baseContent2">
          <div class="labelStyle" style="width: 14vw">实际费用</div>
          <div class="moneyBox">
            <span class="yuan">￥</span>
            <div class="money">
              {{ query.realConsumption }}
            </div>
          </div>
        </div>
        <div class="baseContent3">
          <div
            class="familyUseList"
            v-for="(item, index) in familyRelation"
            :key="index"
          >
            <div>{{ item.type }}的手机</div>
            <div>{{ item.number }}元</div>
          </div>
        </div>
        <div class="baseContent4">
          <div class="labelStyle">合计</div>
          <div class="moneyBox">
            <span class="yuan">￥</span>
            <div class="money">
              {{ total }}
            </div>
          </div>
        </div>
      </div>
      <div style="width: 55.46vw; height: 100%; position: relative" />
    </div>
    <div class="rightBox">
      <div class="baseTitle">推荐套餐</div>
      <div class="baseContent1" style="color: #154ac1; margin-bottom: 5.33vw">
        <div>
          流量
          <span style="padding-left: 2.66vw">{{ setMenu.flow }}G</span>
        </div>
        <div>
          语音
          <span style="padding-left: 2.66vw"> {{ setMenu.voice }}min</span>
        </div>
        <div>
          宽带
          <span style="padding-left: 2.66vw">{{ setMenu.broadband }}M</span>
        </div>
        <div>
          电视
          <span style="padding-left: 2.66vw">{{ setMenu.television }}</span>
        </div>
      </div>
      <div class="driver" />
      <div class="baseContent2">
        <div class="labelStyle">套餐费</div>
        <div class="moneyBox">
          <span class="yuan">￥</span>
          <div class="money">
            {{ menuMoney }}
          </div>
        </div>
      </div>
      <div class="baseContent3-2">
        <div v-if="reasonForCharging.length > 0">
          <div
            class="reasonForChargingList"
            v-for="(item, index) in reasonForCharging"
            :key="index"
          >
            <div
              style="
                font-size: 4.26vw;
                font-weight: Medium;
                color: #5a0a06ff;
                margin: 5.33vw 6.66vw 2.66vw;
              "
            >
              {{ item.reason }}
            </div>
            <div
              style="font-weight: Regular; color: #e63b3bff; margin: 0 6.66vw"
            >
              <span style="font-size: 4.26vw">￥</span
              ><span style="font-size: 6.66vw">{{ item.number }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="baseContent4">
        <div class="labelStyle">优惠价</div>
        <div class="moneyBox">
          <span class="yuan">￥</span>
          <div class="money">
            {{ reasonForChargingTotal }}
          </div>
        </div>
      </div>
      <div class="centerRightIcon" />
    </div>
    <div class="footBox">
      <div class="rankingStyle">
        <div class="rankingFirst">
          <div class="rankingIcon">1</div>
          <div style="flex: 1">
            原计划3年合计{{ total }} × 36 =
            {{ total * 36 }}元，推荐方案3年合计{{ reasonForChargingTotal }} × 36
            = {{ reasonForChargingTotal * 36 }}元，省<span class="yuan">￥</span
            ><span class="money">{{
              (total - reasonForChargingTotal) * 36
            }}</span>
          </div>
        </div>
        <div
          v-for="(item, index) in reasonsForSavingMoney"
          :key="index"
          class="ranking"
        >
          <div class="rankingIcon">{{ index + 2 }}</div>
          <div style="flex: 1">
            {{ item.reason }}，省<span class="yuan">￥</span>
            <span class="money">{{ item.number }}</span>
          </div>
        </div>
      </div>
      <div class="bottomIcon">
        <div class="buttomBox">
          <div class="savingTotal">
            ￥{{ (total - reasonForChargingTotal) * 36 + SavingMoneyTotal }}
          </div>
        </div>
      </div>
    </div>
    <div class="buttonBox">
      <van-button
        type="primary"
        class="buttonStyle"
        style="
          flex: 1;
          background-color: #fff;
          border: 1.5px solid #666666;
          color: #666666;
        "
        round
        @click="turnToEdit"
        >返回</van-button
      >
      <van-button
        type="primary"
        class="buttonStyle"
        style="
          flex: 1;
          background-color: #154ac1ff;
          border: 1.5px solid #fff;
          color: #fff;
        "
        @click="saveAbout"
        round
        >保存</van-button
      >
      <!-- <van-button
        type="default"
        class="buttonStyle"
        @click="showShare = true"
        style="
          background: linear-gradient(
            to right,
            #f090aa,
            #e83422 50%,
            #fda875 100%
          );
          border: 1.5px solid #fff;
          color: #ffffff;
          box-shadow: 0 3px 6px 1px #89580d1a;
          width: 54.4vw;
        "
        round
        >立即分享</van-button
      >
      <van-share-sheet
        v-model:show="showShare"
        title="立即分享给好友"
        :options="options"
        @select="onSelect"
      /> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter, type LocationQueryValue } from 'vue-router'
import { showToast } from 'vant'
import { menuCostList } from '@/api/menu_cost'
import html2canvas from 'html2canvas'

const query = ref<any>(useRoute().query)
const router = useRouter()

const setMenuList = ref([
  {
    type: '5G套餐',
    value: '129套餐',
    number: 129,
    flow: 30,
    voice: 500,
    broadband: 300,
    television: '4K高清',
    other: ''
  },
  {
    type: '5G套餐',
    value: '169套餐',
    number: 169,
    flow: 40,
    voice: 800,
    broadband: 500,
    television: '4K高清',
    other: ''
  },
  {
    type: '5G套餐',
    value: '199套餐',
    number: 199,
    flow: 60,
    voice: 1000,
    broadband: 1000,
    television: '4K高清',
    other: ''
  },
  {
    type: '5G套餐',
    value: '239套餐',
    number: 239,
    flow: 80,
    voice: 1000,
    broadband: 1000,
    television: '4K高清',
    other: ''
  },
  {
    type: '5G套餐',
    value: '299套餐',
    number: 299,
    flow: 100,
    voice: 1000,
    broadband: 1000,
    television: '4K高清',
    other: ''
  },
  {
    type: '三千兆',
    value: '229套餐',
    number: 229,
    flow: 90,
    voice: 1000,
    broadband: 1500,
    television: '4K高清',
    other: ''
  },
  {
    type: '三千兆',
    value: '299套餐',
    number: 299,
    flow: 100,
    voice: 1500,
    broadband: 2000,
    television: '4K高清',
    other: ''
  }
])

const familyRelation = ref(
  JSON.parse(query.value.familyRelation as string)[0]?.type
    ? JSON.parse(query.value.familyRelation as string)
    : []
)
const reasonForCharging = ref(
  JSON.parse(query.value.reasonForCharging as string)[0]?.reason
    ? JSON.parse(query.value.reasonForCharging as string)
    : []
)
const reasonsForSavingMoney = ref(
  JSON.parse(query.value.reasonsForSavingMoney as string)[0]?.reason
    ? JSON.parse(query.value.reasonsForSavingMoney as string)
    : []
)

const total = ref(0)
const reasonForChargingTotal = ref(0)
const SavingMoneyTotal = ref(0)
const setMenu = ref<any>({})
const menuMoney = ref<any>(0)

// 定义一个函数来查找对象
function findMenuItemByTypeAndValue(type: any, value: any) {
  return setMenuList.value.find(
    (item) => item.type === type && item.value === value
  )
}

const showShare = ref(false)
const options = [
  [
    { name: '微信', icon: 'wechat' },
    { name: '朋友圈', icon: 'wechat-moments' },
    { name: '微博', icon: 'weibo' },
    { name: 'QQ', icon: 'qq' }
  ],
  [
    { name: '复制链接', icon: 'link' },
    { name: '分享海报', icon: 'poster' },
    { name: '二维码', icon: 'qrcode' },
    { name: '小程序码', icon: 'weapp-qrcode' }
  ]
]

const onSelect = (option: any) => {
  showToast(option.name)
  showShare.value = false
}

// 方法：处理姓名
const maskName = (name: any) => {
  if (name) {
    const firstChar = name[0]
    return `${firstChar}**`
  }
  return ''
}

// 方法：处理电话号码
const maskPhone = (phone: any) => {
  if (phone) {
    // 显示前3位和后4位，中间用*代替
    const prefix = phone.slice(0, 3)
    const suffix = phone.slice(-4)
    const middleLength = phone.length - 7 // 总长度减去前后显示的位数
    const maskedMiddle = '*'.repeat(middleLength)
    return `${prefix}${maskedMiddle}${suffix}`
  }
  return ''
}

const turnToEdit = () => {
  router.push({
    path: '/register',
    query: {
      tel: query.value.tel,
      name: query.value.name,
      area: query.value.area,
      flow: query.value.flow,
      voice: query.value.voice,
      broadband: query.value.broadband,
      television: query.value.television,
      realConsumption: query.value.realConsumption,
      setMenuType: query.value.setMenuType,
      setMenuNumber: query.value.setMenuNumber,
      discount: query.value.discount,
      familyRelation: query.value.familyRelation,
      reasonForCharging: query.value.reasonForCharging,
      reasonsForSavingMoney: query.value.reasonsForSavingMoney,
      salesman: query.value.salesman
    }
  })
}

// 定义 capturePage 函数
const capturePage = async () => {
  try {
    // 获取整个body元素
    const element = document.body

    // 使用html2canvas将DOM元素转为canvas
    const canvas = await html2canvas(element, {
      useCORS: true, // 如果有跨域图片需要设置为true
      allowTaint: false
    })

    // 从canvas获取图像数据URL
    const image = canvas.toDataURL('image/png')

    // 创建一个隐藏的a标签用于触发下载
    const link = document.createElement('a')
    link.href = image
    link.download = 'page.png' // 下载的图片名称
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    // 清理canvas
    canvas.remove()
  } catch (error) {
    console.error('Capture failed:', error)
  }
}

const saveAbout = async () => {
  const prepareValue = (
    value: LocationQueryValue | LocationQueryValue[]
  ): string | number | undefined => {
    if (Array.isArray(value)) {
      // 如果是数组，可以选择第一个元素作为代表，或者根据需要做其他处理
      return value[0] || undefined
    } else if (value === null) {
      // 如果是 null，返回 undefined
      return undefined
    }
    // 对于数字类型的字段，尝试将其转换为数字
    if (typeof value === 'string' && !isNaN(Number(value))) {
      return Number(value)
    }
    // 否则直接返回原值
    return value
  }

  await menuCostList({
    tel: prepareValue(query.value.tel),
    name: prepareValue(query.value.name),
    area: prepareValue(query.value.area),
    flow: prepareValue(query.value.flow), // 这里假设flow是数字
    voice: prepareValue(query.value.voice), // 假设voice也是数字
    broadband: prepareValue(query.value.broadband),
    television: prepareValue(query.value.television),
    realConsumption: prepareValue(query.value.realConsumption), // 注意这里有个拼写错误，应该是realConsumption
    setMenuType: prepareValue(query.value.setMenuType),
    setMenuNumber: prepareValue(query.value.setMenuNumber),
    discount: prepareValue(query.value.discount), // 假设discount是数字
    familyRelation: Array.isArray(JSON.parse(query.value.familyRelation))
      ? JSON.parse(query.value.familyRelation).map((item: any) => {
          return {
            type: item.type,
            number: parseInt(item.number)
          }
        })
      : [prepareValue(JSON.parse(query.value.familyRelation))],
    reasonForCharging: Array.isArray(JSON.parse(query.value.reasonForCharging))
      ? JSON.parse(query.value.reasonForCharging).map((item: any) => {
          return {
            reason: item.reason,
            number: parseInt(item.number)
          }
        })
      : [prepareValue(JSON.parse(query.value.reasonForCharging))],
    reasonsForSavingMoney: Array.isArray(
      JSON.parse(query.value.reasonsForSavingMoney)
    )
      ? JSON.parse(query.value.reasonsForSavingMoney).map((item: any) => {
          return {
            reason: item.reason,
            number: parseInt(item.number)
          }
        })
      : [prepareValue(JSON.parse(query.value.reasonsForSavingMoney))],
    salesman: prepareValue(query.value.salesman)
  })
  capturePage()
}

onMounted(() => {
  if (familyRelation.value[0]?.type) {
    familyRelation.value.map((item: any) => {
      total.value += parseInt(item.number)
    })
  }
  if (query.value?.realConsumption) {
    total.value += parseInt(query.value.realConsumption as string)
  }

  if (query.value?.setMenuType && query.value?.setMenuNumber) {
    setMenu.value = findMenuItemByTypeAndValue(
      query.value?.setMenuType,
      query.value?.setMenuNumber
    )
  }

  if (query.value?.discount && setMenu.value?.number) {
    console.log(setMenu.value.number, query.value?.discount)

    menuMoney.value =
      setMenu.value.number + parseInt(query.value.discount as string)
    reasonForChargingTotal.value =
      setMenu.value.number + parseInt(query.value.discount as string)
    console.log(menuMoney.value, reasonForChargingTotal.value)
  }
  if (reasonForCharging.value[0]?.reason) {
    reasonForCharging.value.map((item: any) => {
      reasonForChargingTotal.value += parseInt(item.number)
    })
  }
  if (reasonsForSavingMoney.value[0]?.reason) {
    reasonsForSavingMoney.value.map((item: any) => {
      SavingMoneyTotal.value += parseInt(item.number)
    })
  }
})
</script>

<style scoped lang="scss">
.container {
  position: relative;
  overflow: hidden;
  background-image: url('../assets/background.png');
  background-size: cover;
  background-position: center; /* 可选：将图片居中 */
  background-repeat: no-repeat; /* 防止图片重复 */
}

.headerBox {
  position: absolute;
  box-sizing: border-box;
  top: 14.93vw;
  width: calc(100% - 8.96vw);
  height: 36.3vw;
  margin: 0 4.26vw;
  padding: 4.26vw;
  background-image: url('../assets/headerBg.png');
  background-size: cover;
  background-position: center; /* 可选：将图片居中 */
  background-repeat: no-repeat; /* 防止图片重复 */
  display: flex;
  flex-direction: column;
  align-items: center;
}

.firstBox,
.secondBox {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.centerBox {
  position: absolute;
  top: 47vw;
  width: 100%;
  height: 114.93vw;
  background-image: url('../assets/centerBg.png');
  background-size: cover;
  background-position: center; /* 可选：将图片居中 */
  background-repeat: no-repeat; /* 防止图片重复 */
  display: flex;
}

.centerLeft {
  flex: 1;
  position: relative;
}

.baseTitle {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 31.2vw;
  height: 9.6vw;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #ba3d37;
  font-size: 4.8vw;
  background-image: url('../assets/leftTitleBg.png');
  background-size: cover;
  background-position: center; /* 可选：将图片居中 */
  background-repeat: no-repeat; /* 防止图片重复 */
}

.baseContent1 {
  width: calc(100% - 8.53vw);
  height: 34.6vw;
  margin: 14.13vw 4.26vw 2.66vw;
}

.baseContent1 > div {
  font-size: 4.8vw;
  margin-bottom: 2.66vw;
  font-weight: Medium;
}

.baseContent1 > div:last-child {
  margin-bottom: 0;
}

.baseContent2 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 10.6vw;
  margin: 2.66vw 4.26vw 4vw;
}

.baseContent3 {
  box-sizing: border-box;
  width: calc(100% - 8.53vw);
  min-height: 27.73vw;
  padding: 3.2vw 2.66vw;
  margin: 0 4.26vw;
  background-color: #fff;
  border-radius: 1.33vw;
  display: flex;
  flex-direction: column;
}

.baseContent3-2 {
  box-sizing: border-box;
  width: calc(100% - 8.53vw);
  min-height: 26.66vw;
  margin: 0 4.26vw;
  border-radius: 1.33vw;
  width: 48vw;
  display: flex;
  flex-direction: column;
  background-image: url('../assets/chargingBg.png');
  background-size: cover;
  background-position: center; /* 可选：将图片居中 */
  background-repeat: no-repeat; /* 防止图片重复 */
}

.baseContent4 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 2.66vw 4.26vw 0;
}

.familyUseList {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666666;
  font-size: 3.73vw;
  margin-bottom: 2.66vw;
}

.familyUseList:last-child {
  margin-bottom: 0;
}

.rightBox {
  position: absolute;
  top: 44vw;
  right: 0;
  width: 55.46vw;
  height: 121.06vw;
  background-image: url('../assets/rightBg.png');
  background-size: cover;
  background-position: center; /* 可选：将图片居中 */
  background-repeat: no-repeat; /* 防止图片重复 */
}

.centerRightIcon {
  width: 35.2vw;
  height: 35.2vw;
  opacity: 0.6;
  position: absolute;
  bottom: 0;
  right: 0;
  background-image: url('../assets/rightIcon.png');
  background-size: cover;
  background-position: center; /* 可选：将图片居中 */
  background-repeat: no-repeat; /* 防止图片重复 */
}

.footBox {
  position: relative;
  margin-top: 169.33vw;
  width: 100%;
  min-height: 47.67vw;
  background-color: transparent;
}

.driver {
  width: calc(100% - 8.53vw);
  margin: 0 4.26vw;
  background-color: #fff;
  border-bottom: 1px Dashed #000;
}

.labelStyle {
  font-size: 4.8vw;
  font-weight: 700;
}

.moneyBox {
  display: flex;
  justify-content: center;
  align-items: end;
}

.yuan {
  font-size: 5.33vw;
  color: #e63b3b;
}

.money {
  font-size: 7.46vw;
  color: #e63b3b;
  font-weight: 700;
}

.rankingIcon {
  width: 8vw;
  height: 6.67vw;
  margin-right: 2.66vw;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 5.33vw;
  color: #fff;
  background-image: url('../assets/rankingIcon.png');
  background-size: cover;
  background-position: center; /* 可选：将图片居中 */
  background-repeat: no-repeat; /* 防止图片重复 */
}

.discountBox1 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #2a6bfc;
}

.discountBox2 {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #2a6bfc;
}

.rankingStyle {
  margin: 0 4.26vw;
  font-size: 5.33vw;
}

.reasonForChargingList {
  color: #666666;
}

.rankingFirst,
.ranking {
  display: flex;
  align-items: flex-start;
  margin-bottom: 1.86vw;
}

.ranking:last-child {
  margin-bottom: 0;
}

.buttonBox {
  width: calc(100% - 8.53vw);
  margin: 4.26vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

.buttonStyle {
  margin-right: 4.26vw;
}

.bottomIcon {
  position: relative;
  width: 38.4vw;
  height: 23.2vw;
  background-image: url('../assets/bottomIcon.png');
  background-size: cover;
  background-position: center; /* 可选：将图片居中 */
  background-repeat: no-repeat; /* 防止图片重复 */
  float: right;
}

.buttomBox {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  color: #fff;
  position: absolute;
  transform: skewX(-5deg) skewY(5deg) translateX(-50%) translateY(-20%);
  top: 50%;
  left: 50%;
}

.savingTotal {
  font-family: 'Impact', sans-serif; /* 字体 */
  font-size: 6.4vw; /* 字号 */
  font-weight: 700;
  color: rgba(252, 245, 166, 1); /* 文字颜色 */
  text-shadow: 0 0 3.46vw rgba(230, 59, 59, 1); /* 阴影 */
  -webkit-text-stroke: 0.3vw rgba(235, 81, 81, 1); /* 文字描边 */
}
</style>
